# -*- coding: utf-8 -*-
# @File  : proxypool.py
# @Author: ggy
# @Date  : 2019/8/29
# @Software: PyCharm
import redis
import urllib.request as ur
import time

class ProxyPool():
    def __init__(self):
        self.redis_conn = redis.StrictRedis(
            host='localhost',
            port=6379,
            decode_responses=True,
        )

    def set_proxy(self):
        # proxy = ur.urlopen(
        #     'http://api.ip.data5u.com/dynamic/get.html?order=66d0a1878885b01032f307ae83e22b30&sep=3').read().decode(
        #     'utf-8').strip().split(' ')
        # print(proxy)
        proxy_odd = None
        while True:
            proxy_new = ur.urlopen('http://api.ip.data5u.com/dynamic/get.html?order=66d0a1878885b01032f307ae83e22b30&sep=3').read().decode('utf-8').strip().split(' ')
            if proxy_new != proxy_odd:
                proxy_odd = proxy_new
                self.redis_conn.delete('proxy')
                self.redis_conn.sadd('proxy', *proxy_new)
                print('更换代理 ip 为：', proxy_new)
                time.sleep(1)
            else:
                time.sleep(2)


    def get_proxy(self):
        proxy_s = self.redis_conn.srandmember('proxy', 1)
        if proxy_s:
            print(proxy_s[0])
            return proxy_s[0]
        else:
            time.sleep(0.1)
            return self.get_proxy()



if __name__ == '__main__':
    ProxyPool().set_proxy()
    # ProxyPool().get_proxy()